/*******************************************************************************
* This very simple GUI is used to run CV routines.
* 
*
* 
*
* Licensed under GPL Version 3 license (/license.txt).
* Author: Eder A. Perez (eder.perez@ice.ufjf.br)
*******************************************************************************/



#include <GL/glx.h>
#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glut.h>

#include "cvvideo.h"
#include "cvimage.h"

//CVVideoFile *video;
CVVideoV4L2 *video;
CVImage *img;



void configGL() {
  glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
}



void renderScene(void) {

  glClear(GL_COLOR_BUFFER_BIT);
    
  // CVImage is 4 bytes aligned
	glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
	glRasterPos2i(0, 0);
	//video->get_frame(img->data);
	video->getFrame(img->data);
	
	
	/***********************************
	**  Here you put your CV routines **
	***********************************/
	

  /** End of your CV routine **/
	
	
  // Draw frames in the screen
  glDrawPixels(img->width, img->height, GL_RGB, GL_UNSIGNED_BYTE, img->data);
	
  glutSwapBuffers();
}



void changeWindowSize(int w, int h) {

  if(h == 0) h = 1;

  glViewport(0, 0, w, h);

  // Reset the coordinate system before modifying
  glMatrixMode(GL_PROJECTION);
  glLoadIdentity();
	
  // Set the clipping volume
  gluOrtho2D(0.0f, (GLfloat) w, 0.0, (GLfloat) h);
        
  glMatrixMode(GL_MODELVIEW);
  glLoadIdentity();    
}



// This function refresh the screen with new frames
void timerRedisplay(int value) {
  glutPostRedisplay();
  glutTimerFunc(33, timerRedisplay, 1); // Let fps be 30fps
}



int main(int argc, char* argv[]) {

  // Open and configure camera
  //video = new CVVideoFile();
  video = new CVVideoV4L2();
  
  // Open a video file
  //if(!video->open("video3.avi")) {
    //printf("ERROR: %x\n", video->errorcode);
    //exit(video->errorcode);
  //}
  
  // Open a v4l2 camera
  CVv4l2params_t params;
  params.width  = 640;
  params.height = 480;
  params.fps = 25.f;
  params.retrieve_fmt = CV_RETRFMT_RGB24;
  params.device_fmt   = CV_V4L2_DEVFMT_YUYV;

  if(!video->openV4L2("/dev/video0", params)) {
    printf("ERROR: %x\n", video->errorcode);
    exit(video->errorcode);
  }
  
  img = new CVImage();
  img->createImage(video->width, video->height, video->bpp);
  
  // Set up GLUT
  glutInit(&argc, argv);
  glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE);
  glutInitWindowSize(video->width, video->height);
  glutCreateWindow("CV library");
  glutReshapeFunc(changeWindowSize);
  glutDisplayFunc(renderScene);
  glutTimerFunc(33, timerRedisplay, 1);
  //glutIdleFunc(renderScene);
    
  // Set up OpenGL
  configGL();
  
  glutMainLoop();

  return 0;
}
